package com.xcode.unit.util;

import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;

/**
 * @author liuziying
 * @Description 文件工具栏
 * @Date 2021/1/5
 */
public class LFileUtil {

    static Logger logger = LoggerFactory.getLogger(LFileUtil.class);

    /**
     * 过滤路径-获取统一路径格式
     * @param path
     */
    public static String getNewFileDir(String path)  {
        if(StringUtils.isEmpty(path)){
            return path;
        }
        try {
            File file = new File(path);
            if(file.getParentFile().isDirectory()){
                return file.getAbsolutePath();
            }else{
                throw new Exception("传入目录非标准目录名");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }


    /**
     * 文件名.后缀
     * @param pathFileName
     * @return
     */
    public static String getFileName(String pathFileName){
        File srcFile = new File(pathFileName);
        return srcFile.getName();
    }

    /**
     * @param inputFileName 要解压的文件名
     * @param unZipPath 解压的目录*/
    public static void unzip(String inputFileName, String unZipPath) {
        File srcFile = new File(inputFileName);
        if (srcFile.exists()) {
            Project project = new Project();
            Expand expand = new Expand();
            expand.setProject(project);
            expand.setSrc(srcFile);
            expand.setDest(new File(unZipPath));
            expand.execute();
        }else {
            logger.warn("{} 不存在", inputFileName);
        }
    }

    /**
     * @param inputFileName 要解压的文件名
     * @param unZipPath 解压的目录*/
    public static void unjar(String inputFileName, String unZipPath) {
        File srcFile = new File(inputFileName);
        if (srcFile.exists()) {
            try {
                LJarUtil.decompress(inputFileName, unZipPath);
            } catch (IOException e) {
                logger.info("解压异常 {} {}", inputFileName, e.getMessage(), e);
            }
        }else {
            logger.warn("{} 不存在", inputFileName);
        }
    }

    public static void deleteDir(String directory){
        try {
            FileUtils.deleteDirectory(new File(directory));
        } catch (IOException e) {
            logger.error("删除目录异常：{}", e.getMessage(),e);
        }
    }

    /**
     * 创建目录
     * @param directory
     */
    public static void mkDir(String directory){
        try {
            FileUtils.forceMkdir(new File(directory));
        } catch (IOException e) {
            logger.error("创建目录异常：{}", e.getMessage(),e);
        }
    }
}